package com.fagp.mew.cms.permission;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true) //开启security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Bean
    UserDetailsService customUserService(){
        return new CustomUserDetailsService();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService())
                .passwordEncoder(new Md5PasswordEncoder());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()	//验证策略
                    .antMatchers(
                            "/index.html",
                            "/commons/**",
                            "/js/**",
                            "/drag",
                            "/css/**",
                            "/down/**"
                    )
                    .permitAll()
                    .anyRequest()	//所有请求
                    .authenticated()	//需要验证
                    //.antMatchers("/user/**").hasRole("USER")
                .and()
                .formLogin()
                    .loginPage("/login")
                    .loginProcessingUrl("/login/form")
                    .defaultSuccessUrl("/page/index")
                    .successHandler(loginSuccessHandler) //登录成功后可使用loginSuccessHandler()存储用户信息，可选。
                    .failureUrl("/login")
                .permitAll()
                .and()
                .logout()
                    .permitAll()
                .and()
                .headers().frameOptions().disable()
                .and()
                .csrf()
                .disable();

    }




}
